<template>
  <div class="bill-adjustment-result-page">
    <div class="wrap">
      <!-- 顶部步骤条 -->
      <StepBar :steps="steps" :current-step="4" />

      <div class="content">
        <!-- 左侧：基本信息、申请信息、解除记录、账单明细 -->
        <div class="left">
          <!-- 基本信息 -->
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewContract">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 申请信息 -->
          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 解除记录 -->
          <div class="card">
            <div class="card-title">解除记录</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="提交人">{{ formData.terminationSubmitter }}</el-descriptions-item>
              <el-descriptions-item label="解除日期">{{ formData.terminationDate }}</el-descriptions-item>
              <el-descriptions-item label="解除协议" :span="2">
                {{ formData.terminationAgreement }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewTermination">查看</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 账单明细 -->
          <div class="card bill-details-card">
            <div class="card-title">账单明细</div>

            <!-- 1. 应退 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-title">应退</span>
                <span class="section-amount">待扣：{{ billData.refund.items.length }}</span>
                <span class="section-total">小计：{{ refundTotal }} 元</span>
              </div>

              <div class="bill-item" v-for="(item, index) in billData.refund.items" :key="index">
                <div class="bill-row">
                  <span class="label">账单编号：</span>
                  <el-link type="primary" v-if="item.billNo !== '暂无'">{{ item.billNo }}</el-link>
                  <span v-else style="color: #999;">{{ item.billNo }}</span>
                  <el-button type="primary" link size="small" style="margin-left: 10px;" v-if="item.billNo !== '暂无'">月度账单</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ item.month }}</span>
                  <span class="label ml-60">可退金额：</span>
                  <span>{{ item.availableAmount }}元</span>
                </div>
                <div class="bill-row">
                  <span class="label">实缴天数：</span>
                  <span>{{ item.actualDays }} 天</span>
                  <span class="label ml-60">退款天数：</span>
                  <span>{{ item.refundDays }} 天</span>
                </div>
                <div class="bill-row">
                  <span class="label">实退金额：</span>
                  <span class="value-highlight">{{ item.amount }}元</span>
                  <span class="label ml-60" v-if="item.note">调整备注：</span>
                  <span v-if="item.note">{{ item.note }}</span>
                </div>
              </div>
            </div>

            <!-- 2. 欠费 -->
            <div class="bill-section" v-if="billData.arrears.items.length > 0">
              <div class="section-header">
                <span class="section-title">欠费</span>
                <span class="section-amount">待扣：{{ billData.arrears.items.length }}</span>
                <span class="section-total">小计：{{ arrearsTotal }} 元</span>
              </div>

              <div class="bill-item" v-for="(item, index) in billData.arrears.items" :key="index">
                <div class="bill-row">
                  <span class="label">账单编号：</span>
                  <el-link type="primary">{{ item.billNo }}</el-link>
                  <el-button type="primary" link size="small" style="margin-left: 10px;">月度账单</el-button>
                </div>
                <div class="bill-row">
                  <span class="label">账单月份：</span>
                  <span>{{ item.month }}</span>
                </div>
                <div class="bill-row">
                  <span class="label">应付金额：</span>
                  <span>{{ item.amount }} 元</span>
                </div>
              </div>
            </div>

            <!-- 3. 杂费 -->
            <div class="bill-section">
              <div class="section-header">
                <span class="section-title">杂费</span>
                <span class="section-total">小计：{{ miscTotal }} 元</span>
              </div>

              <div class="misc-fee-content">
                <div class="fee-row">
                  <span class="label">可退押金：</span>
                  <span class="value">{{ billData.misc.deposit }} 元</span>
                </div>
                <div class="fee-row">
                  <span class="label">实退金额：</span>
                  <span class="value-highlight">{{ billData.misc.deposit }} 元</span>
                  <span class="label ml-60" v-if="billData.misc.depositNote">调整备注：</span>
                  <span v-if="billData.misc.depositNote">{{ billData.misc.depositNote }}</span>
                </div>
                <div class="fee-row">
                  <span class="label">押金数：</span>
                  <span class="value">{{ billData.misc.deposit }} 元</span>
                </div>
              </div>
            </div>

            <!-- 总计 -->
            <div class="total-summary">
              合计应该金额 = 应退 - 欠费 + 杂费 = {{ billData.totalAmount }} 元
            </div>
          </div>
        </div>

        <!-- 右侧：审批结果、操作记录 -->
        <div class="right">
          <!-- 审批结果 -->
          <div class="card">
            <div class="card-title">审批结果</div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批结果</div>
              <el-radio-group v-model="approvalResult">
                <el-radio label="pass">审批通过</el-radio>
                <el-radio label="reject">审批拒绝</el-radio>
              </el-radio-group>
            </div>
            <div class="result-group">
              <div class="label"><span class="required">*</span>审批意见</div>
              <el-input
                v-model="approvalComment"
                type="textarea"
                :rows="5"
                placeholder="请输入"
                maxlength="200"
                show-word-limit
              />
            </div>
          </div>

          <!-- 操作记录 -->
          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">发起申请-申请退住</div>
                    <div class="timeline-date">2048-10-15 09:00:00</div>
                  </div>
                  <div class="timeline-user">
                    顾廷烨
                    <el-tag size="small" type="success">已发起</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">(待处理) 审批-申请审批</div>
                    <div class="timeline-date">2048-10-15 09:00:00</div>
                  </div>
                  <div class="timeline-user">
                    退住审批员
                    <el-tag size="small" type="success">已通过</el-tag>
                  </div>
                  <div class="timeline-action">
                    <el-button type="primary" link>这是当前审批处</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="bottom-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import StepBar from '@/components/StepBar/index.vue'
import { getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId, submitBillApproval } from '@/api/system/out_management'
import { updateTasks } from '@/api/system/tasks'

const router = useRouter()
const route = useRoute()

// 步骤条数据
const steps = ['申请退住', '申请审批', '解除合同', '调整账单', '账单审批', '退住审批', '费用清算']

// 表单数据
const formData = reactive({
  // 基本信息
  elderlyNo: '',
  elderlyName: '',
  elderlyIdCard: '',
  contact: '',
  feePeriod: '',
  careLevel: '',
  bedNumber: '',
  contract: '',
  consultant: '',
  caregiver: '',
  // 申请信息
  checkoutDate: '',
  checkoutReason: '',
  remark: '',
  applicantName: '',
  submitTime: '',
  // 解除记录
  terminationSubmitter: '',
  terminationDate: '',
  terminationAgreement: ''
})

// 审批表单
const approvalResult = ref('pass')
const approvalComment = ref('')

// ✅ 账单数据（从第四步传递过来）
const billData = reactive({
  // 应退卡片数据
  refund: {
    items: []
  },
  // 欠费卡片数据
  arrears: {
    items: []
  },
  // 杂费卡片数据
  misc: {
    deposit: 0,
    depositNote: ''
  },
  // 计算出的总金额
  totalAmount: '0.00'
})

// ✅ 老人余额信息（balance表数据）
const balanceInfo = reactive({
  elderlyId: null,
  depositBalance: 0,      // 押金余额
  prepaymentBalance: 0,   // 预交款余额
  totalBalance: 0         // 总余额
})

// 欠费项目（保持向后兼容）
const arrearsItems = ref([])

// 计算应退总额
const refundTotal = computed(() => {
  if (!billData.refund.items || billData.refund.items.length === 0) {
    return '0.00'
  }
  const total = billData.refund.items.reduce((sum, item) => {
    return sum + (parseFloat(item.amount) || 0)
  }, 0)
  return total.toFixed(2)
})

// 计算欠费总额
const arrearsTotal = computed(() => {
  if (!billData.arrears.items || billData.arrears.items.length === 0) {
    return '0.00'
  }
  const total = billData.arrears.items.reduce((sum, item) => {
    return sum + (parseFloat(item.amount) || 0)
  }, 0)
  return total.toFixed(2)
})

// 计算杂费总额（押金）
const miscTotal = computed(() => {
  return (parseFloat(billData.misc.deposit) || 0).toFixed(2)
})

// 查看合同
const viewContract = () => {
  if (formData.contract) {
    ElMessage.info('查看合同文件：' + formData.contract)
  } else {
    ElMessage.warning('暂无合同文件')
  }
}

// 查看解除协议
const viewTermination = () => {
  if (formData.terminationAgreement) {
    ElMessage.info('查看解除协议：' + formData.terminationAgreement)
  } else {
    ElMessage.warning('暂无解除协议')
  }
}

// 页面加载时获取数据
onMounted(async () => {
  console.log('=== 账单审批页面加载 ===')
  console.log('Route query:', route.query)
  
  const businessId = route.query.id
  console.log('业务ID:', businessId)
  
  if (!businessId) {
    ElMessage.warning('缺少业务ID参数')
    return
  }
  
  // ✅ 参数验证
  if (!route.query.ptid) {
    ElMessage.error('待办任务ID为空，无法提交！请检查页面参数。')
    console.error('❌ 提交失败：ptid参数为空')
    return
  }

  if (!route.query.taskId) {
    ElMessage.error('工作流任务ID为空，无法提交！请检查页面参数。')
    console.error('❌ 提交失败：taskId参数为空')
    return
  }
  
  try {
    // 1. 获取退住申请详情
    console.log('开始查询退住申请详情...')
    const checkoutRes = await getCheckoutApplicationDetail(businessId)
    console.log('退住申请详情响应:', checkoutRes)
    
    if (checkoutRes.code === 200 && checkoutRes.data) {
      const appData = checkoutRes.data
      console.log('退住申请数据:', appData)
      
      // 填充基本信息（从退住申请中获取）
      formData.elderlyNo = appData.checkOutNo || 'TZ' + businessId
      formData.elderlyName = appData.elderlyName || ''
      formData.elderlyIdCard = appData.elderlyIdCard || ''
      formData.contact = appData.elderlyContact || ''
      formData.careLevel = appData.careLevel || ''
      formData.bedNumber = appData.bedNumber || ''
      formData.contract = appData.contractName || ''
      formData.consultant = appData.caregiverName || '' // ✅ 养老顾问 = 护理员
      formData.caregiver = appData.caregiverName || '' // ✅ 护理员
      
      // 费用期限
      if (appData.feeStartDate && appData.feeEndDate) {
        formData.feePeriod = `${appData.feeStartDate} - ${appData.feeEndDate}`
      }
      
      // 填充申请信息
      formData.checkoutDate = appData.checkOutDate || ''
      formData.checkoutReason = appData.checkOutReason || ''
      formData.remark = appData.remark || ''
      formData.applicantName = appData.creatorName || '护理员a'
      formData.submitTime = appData.createTime || ''
      
      console.log('基本信息已填充:', {
        elderlyName: formData.elderlyName,
        consultant: formData.consultant,
        caregiver: formData.caregiver
      })
      
      console.log('申请信息已填充:', {
        checkoutDate: formData.checkoutDate,
        checkoutReason: formData.checkoutReason,
        applicantName: formData.applicantName
      })
      
      // 2. 如果有老人ID，获取合同信息（主要是解除记录）
      if (appData.elderlyId) {
        console.log('查询老人合同信息, elderlyId:', appData.elderlyId)
        const contractRes = await getContractByElderlyId(appData.elderlyId)
        console.log('合同信息响应:', contractRes)
        
        if (contractRes.code === 200 && contractRes.data) {
          const contractData = contractRes.data
          console.log('合同数据:', contractData)
          
          // 填充解除记录
          if (contractData.terminationSubmitter) {
            // 解除提交人昵称
            if (contractData.sysUser && contractData.sysUser.nickName) {
              formData.terminationSubmitter = contractData.sysUser.nickName
            } else {
              formData.terminationSubmitter = '护理员a'
            }
          }
          
          if (contractData.terminationTime) {
            formData.terminationDate = contractData.terminationTime
          }
          
          if (contractData.terminationAgreement) {
            formData.terminationAgreement = contractData.terminationAgreement
          }
          
          console.log('解除记录已填充:', {
            terminationSubmitter: formData.terminationSubmitter,
            terminationDate: formData.terminationDate,
            terminationAgreement: formData.terminationAgreement
          })
        }
      }
      
      console.log('=== 基本信息加载完成 ===')
    } else {
      ElMessage.error('查询退住申请详情失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败：' + (error.message || '未知错误'))
  }
  
  // ✅ 读取第四步传递过来的账单数据
  console.log('=== 读取账单数据 ===')
  const storageKey = `bill_adjustment_data_${businessId}`
  console.log('尝试从sessionStorage读取:', storageKey)
  
  const savedBillData = sessionStorage.getItem(storageKey)
  if (savedBillData) {
    try {
      const parsedData = JSON.parse(savedBillData)
      console.log('从sessionStorage读取到的账单数据:', parsedData)
      
      // 更新账单数据
      if (parsedData.refund && parsedData.refund.items) {
        billData.refund.items = parsedData.refund.items
        console.log('✅ 应退数据已更新:', billData.refund.items)
      }
      
      if (parsedData.arrears && parsedData.arrears.items) {
        billData.arrears.items = parsedData.arrears.items
        arrearsItems.value = parsedData.arrears.items // 同步到arrearsItems
        console.log('✅ 欠费数据已更新:', billData.arrears.items)
      }
      
      if (parsedData.misc) {
        billData.misc.deposit = parsedData.misc.deposit || 0
        billData.misc.depositNote = parsedData.misc.depositNote || ''
        console.log('✅ 杂费数据已更新:', billData.misc)
      }
      
      if (parsedData.totalAmount) {
        billData.totalAmount = parsedData.totalAmount
        console.log('✅ 总金额已更新:', billData.totalAmount)
      }
      
      // ✅ 读取balance信息
      if (parsedData.balance) {
        balanceInfo.elderlyId = parsedData.balance.elderlyId || null
        balanceInfo.depositBalance = parsedData.balance.depositBalance || 0
        balanceInfo.prepaymentBalance = parsedData.balance.prepaymentBalance || 0
        balanceInfo.totalBalance = parsedData.balance.totalBalance || 0
        console.log('✅ Balance信息已更新:', balanceInfo)
      }
      
      console.log('=== 账单数据加载完成 ===')
      console.log('最终账单数据:', {
        refund: billData.refund,
        arrears: billData.arrears,
        misc: billData.misc,
        balance: balanceInfo,
        totalAmount: billData.totalAmount
      })
      
    } catch (parseError) {
      console.error('解析账单数据失败:', parseError)
      ElMessage.warning('账单数据加载失败，显示默认数据')
      
      // 使用默认数据
      initializeDefaultBillData()
    }
  } else {
    console.log('⚠️ sessionStorage中没有找到账单数据，使用默认数据')
    ElMessage.warning('未找到账单数据，显示默认数据')
    
    // 使用默认数据
    initializeDefaultBillData()
  }
  
  console.log('=== 页面数据加载完成 ===')
})

// 初始化默认账单数据
function initializeDefaultBillData() {
  console.log('初始化默认账单数据...')
  
  billData.refund.items = [
    {
      billNo: 'ZD204810101S000001',
      month: '2048-10',
      availableAmount: 2000.00,
      actualDays: 18,
      refundDays: 12,
      amount: 1800.00,
      note: '扣末尾数无，扣除200元',
      status: '已支付'
    }
  ]
  
  billData.arrears.items = [
    { billNo: 'ZD204810101S000001', month: '2048-10', amount: 2000.00 },
    { billNo: 'ZD204810101S000001', month: '2048-10', amount: 2000.00 },
    { billNo: 'ZD204810101S000001', month: '2048-10', amount: 2000.00 }
  ]
  
  arrearsItems.value = billData.arrears.items
  
  billData.misc.deposit = 2000.00
  billData.misc.depositNote = '扣末尾数无，扣除200元'
  
  billData.totalAmount = '-380.00'
  
  console.log('默认账单数据已设置')
}

// 返回
const handleBack = () => {
  // 返回到待办任务列表
  router.push('/xtgz/xtgz/tasks')
}

// 提交
const handleSubmit = async () => {
  // ✅ 参数验证
  if (!route.query.ptid) {
    ElMessage.error('待办任务ID为空，无法提交！请检查页面参数。')
    console.error('❌ 提交失败：ptid参数为空')
    return
  }

  if (!route.query.taskId) {
    ElMessage.error('工作流任务ID为空，无法提交！请检查页面参数。')
    console.error('❌ 提交失败：taskId参数为空')
    return
  }

  if (!route.query.id) {
    ElMessage.error('业务ID为空，无法提交！')
    console.error('❌ 提交失败：businessId参数为空')
    return
  }

  // 验证审批意见
  if (!approvalComment.value.trim()) {
    ElMessage.warning('请填写审批意见！')
    return
  }

  const resultText = approvalResult.value === 'pass' ? '审批通过' : '审批拒绝'
  
  try {
    await ElMessageBox.confirm(
      `确认提交审批吗？\n审批结果：${resultText}\n审批意见：${approvalComment.value}`,
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 准备提交数据
    const submitData = {
      businessId: route.query.id, // 业务ID
      taskId: route.query.taskId || '', // 工作流任务ID
      ptId: route.query.ptid || '', // 待办任务ID
      opinion: approvalComment.value, // 审批意见
      auditStatus: approvalResult.value === 'pass' ? 1 : 2 // 审核状态：1=通过，2=拒绝
    }

    console.log('=== 账单审批提交 ===')
    console.log('提交数据:', submitData)
    console.log('业务ID:', submitData.businessId)
    console.log('审批结果:', approvalResult.value)
    console.log('审批意见:', approvalComment.value)

    // 调用后端API
    const response = await submitBillApproval(submitData)

    if (response.code === 200) {
      ElMessage.success('账单审批已提交！')
      
      // ✅ 保存账单数据到sessionStorage，供第六步使用
      console.log('=== 保存账单数据到sessionStorage（第五步到第六步）===')
      const billDataForStep6 = {
        // 应退卡片数据
        refund: {
          items: billData.refund.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            availableAmount: item.availableAmount,
            actualDays: item.actualDays,
            refundDays: item.refundDays,
            amount: item.amount,
            note: item.note,
            status: item.status
          }))
        },
        // 欠费卡片数据
        arrears: {
          items: billData.arrears.items.map(item => ({
            billNo: item.billNo,
            month: item.month,
            amount: item.amount,
            status: item.status || '待支付'
          }))
        },
        // 杂费卡片数据
        misc: {
          deposit: billData.misc.deposit,
          depositNote: billData.misc.depositNote
        },
        // ✅ 添加：老人余额信息（balance表数据）
        balance: {
          elderlyId: balanceInfo.elderlyId,
          depositBalance: balanceInfo.depositBalance,     // 押金余额
          prepaymentBalance: balanceInfo.prepaymentBalance, // 预交款余额
          totalBalance: balanceInfo.totalBalance           // 总余额
        },
        // 计算出的总金额
        totalAmount: billData.totalAmount,
        // 保存时间戳
        timestamp: new Date().getTime()
      }
      
      // 保存到sessionStorage（使用业务ID作为key的一部分）
      const storageKey = `bill_data_for_step6_${route.query.id}`
      sessionStorage.setItem(storageKey, JSON.stringify(billDataForStep6))
      console.log('账单数据已保存到sessionStorage（供第六步使用）:', storageKey)
      console.log('保存的数据:', billDataForStep6)
      
      // ✅ 重写：使用最简单直接的方法更新状态
      console.log('=== 重写第五步状态更新逻辑 ===')
      console.log('待办任务ID:', submitData.ptId)
      
      // 方法1：直接调用后端API更新状态
      try {
        console.log('方法1：直接调用后端API更新状态')
        
        // 使用最简单的数据格式
        const simpleUpdateData = {
          id: submitData.ptId,
          isHandle: 1
        }
        
        console.log('简单更新数据:', simpleUpdateData)
        
        const updateResponse = await updateTasks(simpleUpdateData)
        console.log('更新响应:', updateResponse)
        
        if (updateResponse.code === 200) {
          console.log('✅ 方法1成功：第五步待办任务状态更新成功！')
          ElMessage.success('第五步待办任务状态已更新！')
        } else {
          console.error('❌ 方法1失败:', updateResponse.msg)
          throw new Error('方法1失败')
        }
        
      } catch (method1Error) {
        console.error('❌ 方法1异常:', method1Error)
        
        // 方法2：使用更简单的数据格式
        try {
          console.log('方法2：使用更简单的数据格式')
          
          const minimalUpdateData = {
            id: submitData.ptId,
            isHandle: 1,
            updateTime: new Date().getTime() // 使用时间戳
          }
          
          console.log('最小更新数据:', minimalUpdateData)
          
          const updateResponse2 = await updateTasks(minimalUpdateData)
          console.log('更新响应2:', updateResponse2)
          
          if (updateResponse2.code === 200) {
            console.log('✅ 方法2成功：第五步待办任务状态更新成功！')
            ElMessage.success('第五步待办任务状态已更新！')
          } else {
            console.error('❌ 方法2失败:', updateResponse2.msg)
            throw new Error('方法2失败')
          }
          
        } catch (method2Error) {
          console.error('❌ 方法2异常:', method2Error)
          
          // 方法3：只更新必要字段
          try {
            console.log('方法3：只更新必要字段')
            
            const essentialUpdateData = {
              id: submitData.ptId,
              isHandle: 1,
              status: 1
            }
            
            console.log('必要更新数据:', essentialUpdateData)
            
            const updateResponse3 = await updateTasks(essentialUpdateData)
            console.log('更新响应3:', updateResponse3)
            
            if (updateResponse3.code === 200) {
              console.log('✅ 方法3成功：第五步待办任务状态更新成功！')
              ElMessage.success('第五步待办任务状态已更新！')
            } else {
              console.error('❌ 方法3失败:', updateResponse3.msg)
              ElMessage.warning('账单审批提交成功，但状态更新失败')
            }
            
          } catch (method3Error) {
            console.error('❌ 方法3异常:', method3Error)
            ElMessage.warning('账单审批提交成功，但状态更新异常')
          }
        }
      }
      
      // 根据审批结果跳转
      setTimeout(() => {
        if (approvalResult.value === 'pass') {
          // 审批通过：跳转到步骤6（副院长审批退住）
          console.log('=== 第五步跳转到第六步 ===')
          console.log('后端返回数据:', response.data)
          console.log('nextTaskId:', response.data?.nextTaskId)
          console.log('nextPtId:', response.data?.nextPtId)
          
          // ✅ 修复：直接使用后端返回的参数跳转到第六步
          if (response.data?.nextTaskId && response.data?.nextPtId) {
            console.log('✅ 后端返回了第六步参数，直接跳转')
            router.push({
              path: '/splccs/fyzsptz',
              query: {
                id: route.query.id, // 业务ID
                taskId: response.data.nextTaskId, // 第六步的工作流任务ID
                ptid: response.data.nextPtId, // 第六步的待办任务ID
                step: 6,
                type: route.query.type || 1
              }
            })
          } else {
            console.log('❌ 后端未返回第六步的taskId和ptid，跳转到待办任务列表')
            ElMessage.info('审批完成！请从待办任务列表进入下一步。')
            router.push({
              path: '/xtgz/xtgz/tasks'
            })
          }
        } else {
          // 审批拒绝：直接返回待办任务列表
          router.push({
            path: '/xtgz/xtgz/tasks'
          })
        }
      }, 1000)
    } else {
      ElMessage.error(response.msg || '提交失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交异常:', error)
      ElMessage.error('提交失败：' + (error.message || '未知错误'))
    }
  }
}
</script>

<style scoped lang="scss">
.bill-adjustment-result-page {
  min-height: 100%;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 50%, #fffde7 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;

  &::before,
  &::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    opacity: 0.3;
    pointer-events: none;
  }

  &::before {
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(205, 220, 57, 0.3) 0%, transparent 70%);
    top: 100px;
    left: 10%;
  }

  &::after {
    width: 300px;
    height: 300px;
    background: radial-gradient(circle, rgba(139, 195, 74, 0.25) 0%, transparent 70%);
    top: 200px;
    right: 15%;
  }
}

.wrap {
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.content {
  display: grid;
  grid-template-columns: 1fr 450px;
  gap: 20px;
  margin-bottom: 20px;
}

.left,
.right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
}

:deep(.desc) {
  .desc-label {
    background: #fafafa;
    color: #666;
    font-weight: normal;
    text-align: right;
  }
}

/* 账单明细卡片 */
.bill-details-card {
  padding: 25px;
}

.bill-section {
  margin-bottom: 25px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 15px;

  &:last-of-type {
    margin-bottom: 15px;
  }
}

.section-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;

  .section-title {
    font-weight: bold;
    color: #333;
    flex: 1;
  }

  .section-amount {
    color: #666;
    margin-right: 20px;
  }

  .section-total {
    font-weight: bold;
    color: #f56c6c;
  }
}

.bill-item {
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }
}

.bill-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #666;
    min-width: 100px;
  }

  .ml-60 {
    margin-left: 60px;
  }

  .value-highlight {
    color: #f56c6c;
    font-weight: bold;
  }
}

/* 杂费内容 */
.misc-fee-content {
  padding: 15px;
  background: #fafafa;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.fee-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 13px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #666;
    min-width: 100px;
  }

  .value {
    color: #333;
    font-weight: 500;
  }

  .value-highlight {
    color: #f56c6c;
    font-weight: bold;
  }

  .ml-60 {
    margin-left: 60px;
  }
}

/* 总计 */
.total-summary {
  background: #f0f9ff;
  border: 1px solid #d0e8ff;
  border-radius: 4px;
  padding: 12px 16px;
  text-align: center;
  font-size: 14px;
  color: #409eff;
  font-weight: bold;
}

/* 审批表单 */
.result-group {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;

    .required {
      color: #f56c6c;
      margin-right: 4px;
    }
  }

  :deep(.el-radio-group) {
    display: flex;
    gap: 20px;
  }
}

/* 时间轴 */
.timeline {
  .timeline-item {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 21px;
      top: 45px;
      bottom: -25px;
      width: 2px;
      background: #e0e0e0;
    }
  }

  .timeline-icon {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    flex-shrink: 0;

    &.success {
      background: #67c23a;
    }
  }

  .timeline-content {
    flex: 1;
    padding-top: 2px;
  }

  .timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
  }

  .timeline-title {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .timeline-date {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
  }

  .timeline-user {
    font-size: 13px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .timeline-action {
    margin-top: 8px;
  }
}

/* 底部按钮 */
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

@media (max-width: 1200px) {
  .content {
    grid-template-columns: 1fr;
  }
}
</style>

